package com.dw.widget.slideshow.utils;

import java.io.File;

import com.dw.widget.slideshow.db.helper.ImageDBHelper;
import com.dw.widget.slideshow.db.object.ImageData;
import com.dw.widget.slideshow.utils.log.Log;

import android.content.Context;
import android.os.FileObserver;

public class ImageFileObserver extends FileObserver {

	private final String TAG = "ImageFileObserver";
	private final ApplicationEx _APP = ApplicationEx.INSTANCE();
	
	private Context context;
	private String monitorPath;
	
	public ImageFileObserver(Context context, String path) {
		
		super(path);
		this.context = context;
		monitorPath = path;
	}

	@Override
	public void onEvent(int event, String path) {

		String fullPath = String.format("%1$s/%2$s", monitorPath, path);
		
		switch(event)
		{
			case FileObserver.MOVED_TO:
			case FileObserver.CREATE:
			{
				Log.d(context, TAG, String.format("add file %1$s", fullPath));
				
				insert(fullPath);
				break;
			}
			case FileObserver.MOVED_FROM:
			case FileObserver.DELETE:
			{
				Log.d(context, TAG, String.format("remove file %1$s", fullPath));
				
				delete(fullPath);
				break;
			}
			case FileObserver.DELETE_SELF:
			{
				break;
			}
		}
	}
	
	private void insert(String path)
	{
		synchronized (_APP.DB_MODIFY_LOCK) {

			File file = new File(path);
			if(file.isDirectory())     // 为文件夹
			{
				File[] files = ImageUtils.listImageFiles(path);
				AppCommon.insertImages2Db(context, files);
			}
			else   // 为文件
			{
				AppCommon.insertImage2Db(null, context, file);
			}
		}
	}
	
	private void delete(String path)
	{
		synchronized (_APP.DB_MODIFY_LOCK) {
			
			ImageDBHelper dbHelper = new ImageDBHelper(context, _APP.DB_NAME, ImageData.class);
			String sql = String.format("DELETE FROM %1$s WHERE picture_path LIKE '%%2$s%'", 
					dbHelper.getTableName(), path);
			dbHelper.getWritableDatabase().execSQL(sql);
		}
	}
}
